package com.zhy.sunmi.fragment.sell;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.xtoast.XToast;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.greendao.gen.SellGoodHistoryDao;
import com.zhy.greendao.gen.SoldGoodDetailDao;
import com.zhy.sunmi.MyApplication;
import com.zhy.sunmi.R;
import com.zhy.sunmi.bean.SellGoodHistory;
import com.zhy.sunmi.bean.SoldGoodDetail;
import com.zhy.sunmi.utils.ScreenUtils;
import com.zhy.sunmi.utils.XMathUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @author zhouhongyang
 */
public class SubRefundFragment extends Fragment {
    private View rootView;
    private RecyclerView recyclerView_refund;
    private SellGoodHistory sellGoodHistory;
    private List<SoldGoodDetail> soldGoodDetails = new ArrayList<>();
    private TextView tv_totalNum;
    private TextView tv_money;
    private TextView tv_cancel;
    private ConstraintLayout bt_toPay;
    private TextView tv_customerId;
    private String notes;
    private SellGoodHistoryDao sellGoodHistoryDao = MyApplication.getDaoSession().getSellGoodHistoryDao();
    private SoldGoodDetailDao soldGoodDetailDao = MyApplication.getDaoSession().getSoldGoodDetailDao();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_sub_refund, container, false);
            initView(rootView);
        } else {

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void initView(View rootView) {
        initBaseView();
        initRecyclerView();

    }

    private void initBaseView() {
        tv_totalNum = rootView.findViewById(R.id.item_count);
        tv_money = rootView.findViewById(R.id.tv_money);
        tv_cancel = rootView.findViewById(R.id.textView4);
        bt_toPay = rootView.findViewById(R.id.button_topay);
        tv_customerId=rootView.findViewById(R.id.et_customer);

        tv_cancel.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goShopping(0, null, null);
            SellFragment sellFragment = (SellFragment) getParentFragment().getParentFragment();
            sellFragment.changeFragment(1,0,null);
        });
        bt_toPay.setOnClickListener(v -> {
            SubSellingFragment subSellingFragment = (SubSellingFragment) getParentFragment();
            subSellingFragment.goRefundPay(soldGoodDetails,notes);
        });


        rootView.findViewById(R.id.tv_Notes).setOnClickListener(v -> {
            showDialog("Add Notes");

        });


    }


    /**
     * 打折,满减,会员卡,notes,search按钮点击响应dialog
     *
     * @param str 文字标题
     */
    private void showDialog(String str) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_edit, null, false);
       Dialog dialog2 = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog2.show();
        dialog2.setCanceledOnTouchOutside(false);
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog2.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView textView = view.findViewById(R.id.tv_number);
       TextView tv_noticerror = view.findViewById(R.id.textView11);
        textView.setText(str);

        EditText editText = view.findViewById(R.id.et_number);


            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.setText(notes);


        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {

            tv_noticerror.setVisibility(View.INVISIBLE);
            dialog2.dismiss();

        });
        view.findViewById(R.id.tv_confirm).setOnClickListener(v -> {
            String a = editText.getText().toString();

                notes = a;
                dialog2.dismiss();



        });
    }









    private void initRecyclerView() {
        recyclerView_refund = rootView.findViewById(R.id.selling_recyclerview);
        recyclerView_refund.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView_refund.setAdapter(new CommonAdapter<SoldGoodDetail>(getContext(), R.layout.item_selling_good, soldGoodDetails) {
            @Override
            protected void convert(ViewHolder holder, SoldGoodDetail soldGoodDetail, int position) {
                holder.setText(R.id.selling_number, soldGoodDetail.getNumber() + "");
                double b = soldGoodDetail.getPrice();
                BigDecimal p = BigDecimal.valueOf(b);
                String t_price = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPrice()).setScale(2, BigDecimal.ROUND_DOWN).toString();
                holder.setText(R.id.tv_selling_money, "£" + t_price);
                holder.setText(R.id.tv_goodname, soldGoodDetail.getEnglishName());
                holder.setText(R.id.tv_goodCname, soldGoodDetail.getChineseName());
                holder.setText(R.id.tv_good_disoff, new Double(soldGoodDetail.getDiscount()).intValue() + "%");
                holder.setOnClickListener(R.id.iv_ljt, v -> {
                    soldGoodDetails.remove(soldGoodDetail);
                    notifyDataSetChanged();
                    setRefundText();
                });

                holder.itemView.setOnClickListener(v -> {
                    showDialog(soldGoodDetail);
                });




            }
        });
    }




    /**
     * 点击购物车商品列表某项弹出的dialog展示商品信息
     *
     * @param soldGoodDetail
     */
    private void showDialog(SoldGoodDetail soldGoodDetail) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_good_detail2, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        //此处设置位置窗体大小，我这里设置为了手机屏幕宽度的3/4  注意一定要在show方法调用后再写设置窗口大小的代码，否则不起效果会
        dialog.getWindow().setLayout((ScreenUtils.getScreenWidth(getContext()) / 2), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tv_goodname = view.findViewById(R.id.tv_name);
        tv_goodname.setText(soldGoodDetail.getEnglishName());

//        TextView tv_vat = view.findViewById(R.id.tv_vat);
//        tv_vat.setText(sellingGood.getVat() + "%");

        TextView tv_unitprice = view.findViewById(R.id.tv_unitprice);

        tv_unitprice.setText(soldGoodDetail.getPrice() + "");

        EditText et_number = view.findViewById(R.id.et_number);
        et_number.setText(soldGoodDetail.getNumber() + "");

        TextView et_dis = view.findViewById(R.id.et_dis);
        et_dis.setText(soldGoodDetail.getDiscount());


        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setOnClickListener(v -> {

            if(Long.parseLong(et_number.getText().toString())>soldGoodDetail.getNumber()){

                new XToast<>(MyApplication.getInstance())
                .setDuration(1000)
                .setContentView(R.layout.toast_hint)
                        .setAnimStyle(android.R.style.Animation_Activity)
                        .setImageDrawable(android.R.id.icon, R.mipmap.ic_dialog_tip_error)
                        .setText(android.R.id.message, "error")
                        .show();
                return;
            }





            soldGoodDetail.setNumber(Long.parseLong(et_number.getText().toString()));
            recyclerView_refund.getAdapter().notifyDataSetChanged();
            setRefundText();
            dialog.dismiss();
        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });

    }











    public void go(SellGoodHistory sellGoodHistory) {
        if (sellGoodHistory != null) {
            this.sellGoodHistory=sellGoodHistory;
            List<SoldGoodDetail> soldGoodDetails = sellGoodHistory.getSoldGoodDetails();

            List<SellGoodHistory> sellGoodHistoryList=new ArrayList<>();
            sellGoodHistoryList.addAll(sellGoodHistoryDao.queryBuilder().where(SellGoodHistoryDao.Properties.OrderCode.eq(sellGoodHistory.getOrderCode()),SellGoodHistoryDao.Properties.PayStatus.eq(4)).list());


            for(SellGoodHistory sellGoodHistory2:sellGoodHistoryList){

                soldGoodDetails= listrem(soldGoodDetails,sellGoodHistory2.getSoldGoodDetails());


            }




            tv_customerId.setText(sellGoodHistory.getCustomerCode());
            this.soldGoodDetails.clear();
            this.soldGoodDetails.addAll(soldGoodDetails);
            recyclerView_refund.getAdapter().notifyDataSetChanged();
            setRefundText();
        }
    }



    public static List<SoldGoodDetail> listrem(List<SoldGoodDetail> listA,List<SoldGoodDetail> listB){
        for (Iterator<SoldGoodDetail> itA = listA.iterator(); itA.hasNext();)
        {
            SoldGoodDetail temp = itA.next();
            // itA.next() 只能在外层循环里面调用1次
            for (int i = 0; i < listB.size(); i++)
            {
                if (temp.getProductId().equals(listB.get(i).getProductId()))
                // 你不该在这里多次调用itA.next()的
                {
                    if(temp.getNumber()-listB.get(i).getNumber()>0){
                        temp.setNumber(temp.getNumber()-listB.get(i).getNumber());
                    }else {
                        itA.remove();
                    }
                }





            }
        }
        return listA;
    }









    private void setRefundText() {
        long number = 0;
        BigDecimal totalmoney = new BigDecimal(0);
        for (SoldGoodDetail soldGoodDetail : soldGoodDetails) {
            number += soldGoodDetail.getNumber();
            BigDecimal t_price = XMathUtil.multiply(soldGoodDetail.getNumber(), soldGoodDetail.getPrice()).setScale(2, BigDecimal.ROUND_DOWN);
            totalmoney = XMathUtil.add(totalmoney, t_price);
        }

        tv_totalNum.setText(number + "  items");
        tv_money.setText("£" + totalmoney);

    }


}